import { computed, createVNode, Ref } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { Modal, message } from "ant-design-vue";
import { checkStatusApi, deptAccountExcelApi, getDeptAccountPageApi, updateStatusApi } from "@/api/configCenter/accountKeeper";
import { listByBusinessIdApi } from "@/api/waybillManagement/businessWaybill";
export default function OperationHook(state: {
  searchForm: AccountKeeper.SearchForm;
  tableData: Ref<Array<AccountKeeper.ListRows>>;
  dialogOpts: Base.DialogOpts;
  loading: Ref<boolean>;
  drawerOpts: Base.DrawerOpts;
  tableRef: Ref<any>;
  upLoadType: Ref<string>;
  getUpdateOptions: Map<string, any>;
  upLoadTemplate: Ref<number>;
}) {
  const { searchForm, tableData, dialogOpts, loading, drawerOpts, tableRef, upLoadType, getUpdateOptions, upLoadTemplate } = state;
  const selectRows = computed<Array<AccountKeeper.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const getData = () => {
    const params = {
      ...getParams()
    };
    loading.value = true;
    return getDeptAccountPageApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const searchHandle = () => {
    searchForm.pageNum = 1;
    getData();
  };

  const getParams = () => {
    const { shortNameList, name, receiveAccount, openBankList, deptIdList, accountPropertiesList, currencyList, paymentMethodList, pageNum, pageSize, total } = searchForm;

    const params: AccountKeeper.SearchFormParmas = {
      shortNameList: [],
      name,
      receiveAccount,
      openBankList,
      deptIdList,
      accountPropertiesList,
      currencyList,
      paymentMethodList,
      pageNum,
      pageSize,
      total
    };

    if (shortNameList)
      params.shortNameList = shortNameList
        .trim()
        .replace(/,{1,}|,{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");

    return params;
  };
  const editHandle = (row: AccountKeeper.ListRows) => {
    drawerOpts.title = "编辑";
    drawerOpts.width = "1200px";
    drawerOpts.type = 2;
    drawerOpts.component = "AddAccountKeeper";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  const addHandle = () => {
    drawerOpts.title = "新增";
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "AddAccountKeeper";
    drawerOpts.visible = true;
  };
  const showHandle = (row: AccountKeeper.ListRows) => {
    drawerOpts.title = "查看";
    drawerOpts.width = "1200px";
    drawerOpts.type = 3;
    drawerOpts.component = "AddAccountKeeper";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };

  const importCarrierHandle = () => {
    dialogOpts.title = "导入账户";
    dialogOpts.width = "520px";
    dialogOpts.component = "UploadFileAndErrorTemplate";
    dialogOpts.visible = true;
  };

  // const importCarrierFn = (from: any) => {
  //   return importCarrierApi(from);
  // };

  // 修改状态
  const changeStatusHandle = async (number: number) => {
    const repetition = Array.from([...new Set(selectRows.value.map((t: any) => t.status))]);
    if ((repetition.length > 1 && number === 1) || (repetition.length === 1 && repetition.includes(number))) return message.error("仅限启用状态账号修改为停用状态，请重新勾选启用账号!");
    if ((repetition.length > 1 && number === 0) || (repetition.length === 1 && repetition.includes(number))) return message.error("仅限停用状态账号修改为启用状态，请重新勾选停用账号!");

    if (!selectRows.value.length) return message.error("请勾选数据再进行操作");

    const params: { idList: Array<string>; status: number } = {
      idList: selectRows.value.map(({ id }) => id),
      status: number
    };

    const check: any = await checkStatusApi(params);
    const { code, data } = check;
    //启用
    if (code === 200 && number === 1) {
      Modal.confirm({
        title: data
          ? "启用后，该账号可恢复正常使用，系统内可产生流水，且可同步账单，是否确认启用该账号？"
          : "该账户下存在多个同一账号,同一账号仅限支持1个账号为启用状态!若启用该账号,其他同一账号默认为停用状态。启用后,该账号可恢复正常使用,系统内可产生流水,且支持同步账单,是否确认启用该账号？",
        icon: createVNode(ExclamationCircleOutlined),
        content: "",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          updateStatusApi(params).then((res: any) => {
            const { code } = res;
            if (code === 200) {
              message.success("操作成功!");
              getData();
            }
          });
        }
      });
    }
    //禁用
    if (code === 200 && number === 0) {
      Modal.confirm({
        title: "停用后，该账号将不可用，系统内停止产生流水，且不再同步账单，是否确认停用该账号？",
        icon: createVNode(ExclamationCircleOutlined),
        content: "",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          updateStatusApi(params).then((res: any) => {
            const { code } = res;
            if (code === 200) {
              message.success("操作成功!");
              getData();
            }
          });
        }
      });
    }
  };

  //日志
  const showLogHandle = (row: WarehouseEntryChannel.ListRows | undefined) => {
    drawerOpts.title = "日志";
    drawerOpts.width = "1200px";
    drawerOpts.passData = row;
    drawerOpts.component = "OperationLog";
    drawerOpts.type = 2;
    drawerOpts.visible = true;
  };
  const requestFn = () => {
    return listByBusinessIdApi({ businessId: drawerOpts.passData?.id, sysModule: "账户管理" });
  };

  //导入
  const importProblemHandle = (type: string, number: number) => {
    dialogOpts.title = `导入账户`;
    dialogOpts.width = "500px";
    dialogOpts.component = "UploadfileAndDownLoadTemplate";
    dialogOpts.visible = true;
    upLoadType.value = type;
    upLoadTemplate.value = number;
  };
  //上传文件回调
  const upLoadRequestFn = (from: File) => {
    const MapRequest = getUpdateOptions.get(upLoadType.value);
    return MapRequest(from);
  };
  //导出
  const deptAccountExcelHandle = () => {
    const prams: any = selectRows.value.length ? { list: selectRows.value } : { ...getParams() };

    loading.value = true;
    return deptAccountExcelApi(prams)
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          message.success("创建任务成功，请前往导出中心下载！");
          getData();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  return {
    searchHandle,
    getData,
    editHandle,
    addHandle,
    importCarrierHandle,
    // importCarrierFn,
    changeStatusHandle,
    showHandle,
    showLogHandle,
    requestFn,
    upLoadRequestFn,
    importProblemHandle,
    deptAccountExcelHandle
  };
}
